<template>
    <el-aside style="background-color:#fff; border-right: 1px solid #ebeef5; padding: 10px;width: 100%;">
        <div style="margin-bottom: 20px;">
            <el-button type="primary" plain icon="Plus" @click="createWorkspace" style="width: 100%">
                新建工作区
            </el-button>
        </div>
        <el-collapse v-model="activeName" accordion @change="handleChange">
            <el-collapse-item v-for="(workspace, index) in workspaces" :key="workspace.slug" :name="index">
                <template slot="title">
                    <div
                        style="display: flex; justify-content: space-between; width: 100%; align-items: center;font-size: 14px;">
                        {{ workspace.name }}
                        <div style="font-size: 16px;"><i
                                class="el-icon-setting" @click.stop="settingBtn(workspace)"></i>
                        </div>
                    </div>
                </template>
                <el-menu :default-active="activeThreadSlug" @select="handleThreadSelect" style="border-right: none">
                    <el-menu-item v-for="thread in workspace.threads" :key="thread.slug" :index="thread.slug">
                        <div style="display: flex; justify-content: space-between; align-items: center;">
                            <div>{{ thread.name }}</div>
                            <div>
                                <el-dropdown @command="handleCommand">
                                    <span class="el-dropdown-link">
                                        <i class="el-icon-more"></i>
                                    </span>
                                    <el-dropdown-menu slot="dropdown">
                                        <el-dropdown-item
                                            :command="['重命名', workspace.slug, thread.slug]">重命名</el-dropdown-item>
                                        <el-dropdown-item
                                            :command="['删除', workspace.slug, thread.slug]">删除</el-dropdown-item>
                                    </el-dropdown-menu>
                                </el-dropdown>
                            </div>
                        </div>
                    </el-menu-item>
                </el-menu>
                <div style="width: 100%;padding-top: 5px;">
                    <el-button style="width: 100%;" @click="createThread(workspace.slug)"
                        icon="el-icon-plus">新增方法</el-button>
                </div>
            </el-collapse-item>
        </el-collapse>
        <!-- 重命名弹窗 -->
        <rename-thread-dialog ref="renameThreadDialog" :visible="showRenameDialog" :threadSlug="currentThreadSlug"
            :workspaceSlug="currentWorkspaceSlug" @close="showRenameDialog = false" @rename="renameThread" />
    </el-aside>
</template>

<script>
import { threadsApi,workspacesApi } from '../../api/aigc/index'; // 引入封装好的 API
import RenameThreadDialog from './RenameThreadDialog.vue';
export default {
    data() {
        return {
            activeName: '1',  // 默认打开的工作区
            showRenameDialog: false,  // 控制弹窗显示
            currentThreadSlug: null,  // 当前正在重命名的线程 slug
            currentWorkspaceSlug: null, // 当前工作区的 slug
        };
    },
    components: {
        RenameThreadDialog
    },
    props: {
        workspaces: Array,
        activeThreadSlug: {
            type: [String, Number, null],
            required: false
        },
    },
    methods: {
        handleThreadSelect(threadSlug) {
            console.log(threadSlug);

            this.$emit('thread-select', threadSlug);  // 触发事件，通知父组件选中哪个线程
        },

        // 监听命令（如：重命名、删除）
        handleCommand([command, workspaceSlug, threadSlug]) {
            console.log('Command received:', command, workspaceSlug, threadSlug); // 调试用，查看 command 值
            if (command === '重命名') {
                this.openRenameDialog(workspaceSlug, threadSlug); // 打开重命名弹窗
            } else if (command === '删除') {
                this.deleteThread(workspaceSlug, threadSlug); // 删除线程
            }
        },

        // 打开重命名弹窗
        openRenameDialog(workspaceSlug, threadSlug) {
            this.showRenameDialog = true;
            this.currentThreadSlug = threadSlug;
            this.currentWorkspaceSlug = workspaceSlug;
            const thread = this.workspaces
                .find(ws => ws.slug === workspaceSlug)
                .threads.find(t => t.slug === threadSlug);
            this.$nextTick(() => {
                this.$refs.renameThreadDialog.newName = thread.name;
            });
        },

        async renameThread(newName) {
            try {
                await threadsApi.updateThread(this.currentWorkspaceSlug, this.currentThreadSlug, newName);
                const workspace = this.workspaces.find(ws => ws.slug === this.currentWorkspaceSlug);
                const thread = workspace.threads.find(t => t.slug === this.currentThreadSlug);
                thread.name = newName;
                this.$message.success('线程名称更新成功');
            } catch (error) {
                console.error("Error renaming thread:", error);
                this.$message.error('更新线程名称失败');
            } finally {
                this.showRenameDialog = false;
            }
        },

        async deleteThread(workspaceSlug, threadSlug) {
            try {
                await threadsApi.deleteThread(workspaceSlug, threadSlug);
                const workspace = this.workspaces.find(ws => ws.slug === workspaceSlug);
                workspace.threads = workspace.threads.filter(t => t.slug !== threadSlug);
                this.$message.success('线程已删除');
            } catch (error) {
                console.error("Error deleting thread:", error);
                this.$message.error('删除线程失败');
            }
        },

        createWorkspace() {
            this.$emit('workspace-create');
        },

        async createThread(workspaceSlug) {
            const threadData = {
                name: 'Thread',
            };
            try {
                const response = await threadsApi.createThread(workspaceSlug, threadData);
                const updatedWorkspace = this.workspaces.find(ws => ws.slug === workspaceSlug);
                updatedWorkspace.threads.push(response.thread);
                this.$emit('thread-select', response.thread.slug);
            } catch (error) {
                console.error("Error creating thread:", error);
            }
        },
        handleChange(val) {
            this.$emit('change', val); // 触发工作区切换事件
        },
        async settingBtn(workspace) {
            this.$emit('setting',workspace)
        }
    }
};
</script>

<style scoped>
.el-menu-item {
    height: 45px;
    line-height: 45px;
}

.el-menu-item.is-active {
    border: 1px solid #409EFF;
    border-radius: 5px;
    background-color: #ECF5FF;
}
</style>


<style scoped>
.el-menu-item {
    height: 45px;
    line-height: 45px;
}

.el-menu-item.is-active {
    border: 1px solid #409eff;
    border-radius: 5px;
    background-color: #ecf5ff;
}

.el-collapse-item__content {
    padding: 0px;
}
</style>
